package generation

import (
	"bytes"
	"fmt"
	"net/http"
)

// ClusterConfig 包含连接集群所需的信息
type ClusterConfig struct {
	Name        string
	Server      string
	BearerToken string
}

func createJob(jenkinsURL, user, apiToken, jobName, viewName string, configXML []byte) {
	req, err := http.NewRequest("POST", jenkinsURL+"/createItem?name="+jobName, bytes.NewBuffer(configXML))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}

	req.Header.Set("Content-Type", "application/xml")
	req.SetBasicAuth(user, apiToken)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request to Jenkins:", err)
		return
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		fmt.Println("Failed to create job, status code:", resp.StatusCode)
		return
	}

	fmt.Println("Jenkins job created successfully, URL: http://mind-jenkins.im30.lan/job/" + jobName)

	// 将任务添加到视图
	addToView(jenkinsURL, user, apiToken, viewName, jobName)
}

func addToView(jenkinsURL, user, apiToken, viewName, jobName string) {
	data := []byte("name=" + jobName)
	req, err := http.NewRequest("POST", jenkinsURL+"/view/"+viewName+"/addJobToView", bytes.NewBuffer(data))
	if err != nil {
		fmt.Println("Error creating request to add job to view:", err)
		return
	}

	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.SetBasicAuth(user, apiToken)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request to add job to view:", err)
		return
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		fmt.Println("Failed to add job to view, status code:", resp.StatusCode)
	} else {
		fmt.Println("Job successfully added to view:", viewName)
	}
}
